package cn.edu.flink.tutorial.cep.app;

import cn.edu.flink.tutorial.cep.bean.LoginEvent;
import cn.edu.flink.tutorial.cep.bean.Warning;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.IterativeCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;
import java.util.List;
import java.util.Map;


// 检测一个用户在3秒内连续3次登陆失败
public class LoginFailWithCep {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<String> streamSource = env.readTextFile("src/main/resources/LoginLog.csv");

        SingleOutputStreamOperator<LoginEvent> loginEventDS = streamSource.map(LoginEvent::fromString);

//        loginEventDS.print("loginEvent");

        // watermarks
        WatermarkStrategy<LoginEvent> loginEventWatermarkStrategy = WatermarkStrategy
                .<LoginEvent>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                .withTimestampAssigner(new SerializableTimestampAssigner<LoginEvent>() {
                    @Override
                    public long extractTimestamp(LoginEvent loginEvent, long l) {
                        return loginEvent.getEventTime() * 1000L;
                    }
                });

        SingleOutputStreamOperator<LoginEvent> loginEventWithEventTimeDS = loginEventDS
                .assignTimestampsAndWatermarks(loginEventWatermarkStrategy);

        KeyedStream<LoginEvent, Long> loginEventKeyedStream = loginEventWithEventTimeDS
                .keyBy(LoginEvent::getUserId);


        Pattern<LoginEvent, LoginEvent> loginFailPattern = Pattern
                .<LoginEvent>begin("one")
                .where(new IterativeCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent loginEvent, Context<LoginEvent> context) throws Exception {
                        return "fail".equalsIgnoreCase(loginEvent.getEventType());
                    }
                })
                .times(3)  // 默认匹配1次
                //默认使用宽松近邻
                // .consecutive()  //严格紧邻
                .within(Time.seconds(3));


        PatternStream<LoginEvent> patternStream = CEP.pattern(loginEventKeyedStream, loginFailPattern);
        SingleOutputStreamOperator<Warning> warningDS = patternStream.select(new PatternSelectFunction<LoginEvent, Warning>() {
            @Override
            public Warning select(Map<String, List<LoginEvent>> map) throws Exception {
                System.out.println(map);
                LoginEvent one = map.get("one").get(0);
                LoginEvent three = map.get("one").get(2);
                return new Warning(one.getUserId(), one.getEventTime(), three.getEventTime(), "login fail!");
            }
        });

        warningDS.print("warning");

        env.execute();


    }
}
